﻿using PagedList;
using PagedList.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using GiaoTrinhEPU.Repositories.Repositories;
using GiaoTrinhEPU.Repositories.DataModels;
using GiaoTrinhEPU.Repositories;
using GiaoTrinhEPU.Repositories.Interfaces;
using GiaoTrinhEPU.Core.ActionResults;
using GiaoTrinhEPU.Core;

namespace GiaoTrinhEPU.Areas.Manager.Controllers
{
    public class PrintController : BaseController
    {
        /// <summary>
        /// Declare Print Repository
        /// </summary>
        private PrintRepository printRepository;

        /// <summary>
        ///  Declare Session
        /// </summary>
        public static string SessionPrintSort = "SessionPrintSort";
        public static string SessionPrintSearch = "SessionPrintSearch";
        public static string SessionPrintSortOpt = "SessionPrintSortOpt";



        // GET: /Print/
        /// <summary>
        /// Constructor that allow to create a Comment controller
        /// </summary>
        public PrintController()
            : base()
        {
            this.printRepository = new PrintRepository();
            ViewBag.SelectedMenuId = 25;
        }

        public ActionResult Index(int page = 1, int size = 25, String search = "", String opt = "", String sort = "")
        {
            ViewBag.Title = "Kế Hoạch In";
            // Stored Session
            
            Session[SessionPrintSort] = sort.Trim().Length > 0 ? sort.ToLower() : Session[SessionPrintSort];
            Session[SessionPrintSortOpt] = opt.Trim().Length > 0 ? opt.ToLower() : Session[SessionPrintSortOpt];

            var print = this.printRepository.ListPrints(false).ToList();

            // Search
            if (Session[SessionPrintSearch] != null)
            {
                ViewBag.Keyword = Session[SessionPrintSearch].ToString();

                print = print.Where(l => l.Name.ToUpper().Contains(ViewBag.Keyword.ToUpper())).ToList();

            }
            // Sort 
            ViewBag.SortNameOpt = "desc";
            if (Session[SessionPrintSort] != null)
            {
                switch (Session[SessionPrintSort].ToString())
                {
                    case "name":
                        print = Session[SessionPrintSortOpt].ToString().Equals("desc") ? print.OrderByDescending(s => s.Name).ToList() : print.OrderBy(s => s.Name).ToList();

                        Session[SessionPrintSort] = "name";
                        ViewBag.SortNameOpt = Sort.SetSortOrderOption(Session[SessionPrintSortOpt].ToString());
                        break;

                    default:
                        break;
                }
            }


            return View(print.ToPagedList(page, size));
        }
        /// <summary>
        /// Get
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Create()
        {
            var printModel = new PrintModel();
            printModel.CreatedBy = User.Identity.Name;
            printModel.CreatedDate = DateTime.Now;
            printModel.ModifiedDate = printModel.CreatedDate;
            printModel.PDate = DateTime.Now.Date;
            return View(printModel);
        }
        /// <summary>
        /// create action with param
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Create(PrintModel model)
        {
            ViewBag.EnabledMenu = false;

            if (!ModelState.IsValid)
            {
                return View("Create");
            }
            else
            {
                if (this.printRepository.HasNameExisted(model.Name) == true)
                {
                    return View("Create").WithErrorMessage("Tên bản in  đã được sử dụng");
                }


                var print = new Print();
                print.Id = (int)model.Id;
                print.Name = model.Name;
                print.Quantum = (int)model.Quantum;
                print.PDate = model.PDate;
                print.CreatedBy = model.CreatedBy;
                print.CreatedDate = model.CreatedDate;
                print.ModifiedCount = (byte)model.ModifiedCount;
                print.ModifiedDate = model.ModifiedDate;
                print.ModifiedBy = model.ModifiedBy;
                print.Description = model.Description;

                this.printRepository.CreatePrint(print);
                // Returns view with successful message
                return RedirectToAction("Index").WithSuccessMessage("Đã tạo thành công bản in  mới"); ;
            }
        }
        /// <summary>
        ///  Edit action 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Edit(int id = 0)
        {
            ViewBag.EnabledMenu = false;

            var print = this.printRepository.GetPrintById(id);
            var printModel = new PrintModel(print);

            // population dropdow list
         

            return View(printModel);
        }
        /// <summary>
        ///  Edit action 
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(PrintModel model)
        {
            ViewBag.EnabledMenu = false;

            if (!ModelState.IsValid)
            {
                return View("Edit");
            }
            else
            {
                if (this.printRepository.HasNameDuplicated(model.Id, model.Name) == true)
                {
                    return View("Edit").WithErrorMessage("Tên bản in  đã được sử dụng");
                }

                var print = new Print();

                print.Id = (int)model.Id;
                print.Id = (int)model.Id;
                print.Name = model.Name;
                print.Quantum = (int)model.Quantum;
                print.PDate = model.PDate;
                print.CreatedBy = model.CreatedBy;
                print.CreatedDate = model.CreatedDate;
                print.ModifiedCount = (byte)model.ModifiedCount;
                print.ModifiedDate = model.ModifiedDate;
                print.ModifiedBy = model.ModifiedBy;
                print.Description = model.Description;

                this.printRepository.UpdatePrint(print);

                return RedirectToAction("Index").WithSuccessMessage("Đã sửa thành công bản in  này");

            }
        }
        /// <summary>
        /// Delete action 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Delete(int id)
        {
            this.printRepository.DeletePrint(id);
            return RedirectToAction("Index").WithSuccessMessage("Đã xóa thành công bản in  này"); ;
        }

        /// <summary>
        ///  Delete Multi
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ActionResult DeleteMulti(int[] ids = null)
        {
            if (ids == null || ids.Length == 0)
            {
                return RedirectToAction("Index");
            }

            for (int i = 0; i < ids.Length; i++)
            {
                int id = ids[i];

                this.printRepository.DeletePrint(id);
            }

            return RedirectToAction("Index").WithSuccessMessage("Đã xóa thành công những bản in  này");
        }
        /// <summary>
        /// Clear
        /// </summary>
        /// <returns></returns>
        public ActionResult Clear()
        {
            // Clear sessions
            Session[SessionPrintSearch] = null;
            Session[SessionPrintSort] = null;
            Session[SessionPrintSortOpt] = null;

            return RedirectToAction("Index");
        }
        /// <summary>
        /// check name avaiable
        /// </summary>
        /// <param name="name"></param>
        /// <param name="Id"></param>
        /// <returns></returns>
        public JsonResult IsNameAvaiable(String name, int Id = 0)
        {
            if (Id == 0)
            {
                if (!this.printRepository.HasNameExisted(name))
                {
                    return Json(true, JsonRequestBehavior.AllowGet);
                }
            }
            else
            {
                if (!this.printRepository.HasNameDuplicated(Id, name))
                {
                    return Json(true, JsonRequestBehavior.AllowGet);
                }


            }

            return Json("Tên bản in  đã được sử dụng", JsonRequestBehavior.AllowGet);
        }
    }
}
